package service

import (
	"context"
	com_model "elflog/common/com-model"
	"elflog/common/errs"
	"elflog/common/utils/id_util"
	"elflog/common/utils/pswd_util"
	"elflog/module/module-account/model"
	"github.com/jinzhu/gorm"
	"time"
)

func (a *ModuleAccountService) CreateAccount(ctx context.Context, loginName, password string) (id string, err error) {
	salt := pswd_util.GetSalt(6)
	accountId := id_util.GetUuid()
	err = a.dao.Dao.GetDb(ctx).Create(&model.AccountMaster{
		Model: com_model.Model{
			Id:        accountId,
			CreatedAt: time.Now(),
			UpdatedAt: time.Now(),
			DeletedAt: nil,
		},
		LoginName: loginName,
		Password:  pswd_util.GetMd5Password(password, salt),
		Salt:      salt,
	}).Error
	if err != nil {
		return "", errs.NewInternal().WithError(err)
	}
	return accountId, nil
}

func (a *ModuleAccountService) GetAccountByLoginName(ctx context.Context, loginName string) (*model.AccountMaster, error) {
	account := new(model.AccountMaster)
	db := a.dao.Dao.GetDb(ctx).Model(account)
	err := db.First(account, "login_name=?", loginName).Error
	if err != nil {
		if gorm.IsRecordNotFoundError(err) {
			return nil, nil
		}
		return nil, err
	}
	return account, nil
}
